#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Web应用权限绕过检测工具 - Kali 2025版
版本: 3.0
功能: 结合Kali 2025工具，检测权限绕过漏洞
作者: 顶级渗透测试工程师
"""

import os
import sys
import requests
import urllib3
import json
import time
from urllib.parse import urljoin, urlparse, parse_qs
from bs4 import BeautifulSoup
import re
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta
import hashlib
import random
import string
from pathlib import Path
import signal
import psutil
import jwt
import uuid
from urllib.parse import unquote
import base64
import hmac
import hashlib
from cryptography.fernet import Fernet
import asyncio
import aiohttp
from typing import Dict, List, Optional, Tuple, Any
import subprocess
import tempfile

# 禁用SSL证书验证警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class KaliToolIntegrator:
    """Kali工具集成器"""
    def __init__(self):
        self.tools = {
            'nikto': self._run_nikto,
            'dirb': self._run_dirb,
            'gobuster': self._run_gobuster,
            'sqlmap': self._run_sqlmap,
            'nmap': self._run_nmap,
            'whatweb': self._run_whatweb
        }
    
    def _run_nikto(self, target: str) -> Dict:
        """运行Nikto扫描"""
        try:
            cmd = [
                "nikto",
                "-h", target,
                "-output", "/tmp/nikto_temp.txt",
                "-C", "all",
                "-ask", "no",
                "-maxtime", "120"
            ]
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            
            vulnerabilities = []
            if result.returncode == 0:
                lines = result.stdout.split('\n')
                for line in lines:
                    if 'VULNERABLE' in line.upper() or 'UNAUTHORIZED' in line.upper():
                        vulnerabilities.append(line.strip())
            
            return {
                'success': result.returncode == 0,
                'output': result.stdout,
                'vulnerabilities': vulnerabilities,
                'error': result.stderr if result.returncode != 0 else None
            }
        except subprocess.TimeoutExpired:
            return {
                'success': False,
                'output': '',
                'vulnerabilities': [],
                'error': 'Nikto扫描超时'
            }
        except Exception as e:
            return {
                'success': False,
                'output': '',
                'vulnerabilities': [],
                'error': str(e)
            }
    
    def _run_dirb(self, target: str) -> Dict:
        """运行Dirb扫描"""
        try:
            # 创建临时字典文件
            temp_dict = f"/tmp/dirb_dict_{random.randint(1000, 9999)}.txt"
            with open(temp_dict, 'w') as f:
                # 写入一些常见的用户相关路径
                user_paths = [
                    'admin', 'user', 'users', 'profile', 'account', 'dashboard',
                    'api/users', 'api/user', 'api/admin', 'admin/users', 'admin/user'
                ]
                f.write('\n'.join(user_paths))
            
            cmd = [
                "dirb",
                target,
                temp_dict,
                "-o", "/tmp/dirb_temp.txt",
                "-r", "-S", "-t", "1"
            ]
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            
            unauthorized_paths = []
            if result.returncode == 0:
                lines = result.stdout.split('\n')
                for line in lines:
                    if '+ http' in line and ('200' in line or '403' in line):
                        match = re.search(r'\+ http.*?(\S+)', line)
                        if match:
                            unauthorized_paths.append(match.group(1))
            
            # 清理临时文件
            if os.path.exists(temp_dict):
                os.remove(temp_dict)
            
            return {
                'success': result.returncode == 0,
                'output': result.stdout,
                'unauthorized_paths': unauthorized_paths,
                'error': result.stderr if result.returncode != 0 else None
            }
        except subprocess.TimeoutExpired:
            return {
                'success': False,
                'output': '',
                'unauthorized_paths': [],
                'error': 'Dirb扫描超时'
            }
        except Exception as e:
            return {
                'success': False,
                'output': '',
                'unauthorized_paths': [],
                'error': str(e)
            }
    
    def _run_gobuster(self, target: str) -> Dict:
        """运行Gobuster扫描"""
        try:
            # 创建临时字典文件
            temp_dict = f"/tmp/gobuster_dict_{random.randint(1000, 9999)}.txt"
            with open(temp_dict, 'w') as f:
                # 写入一些常见的用户相关路径
                user_paths = [
                    'admin', 'user', 'users', 'profile', 'account', 'dashboard',
                    'api/users', 'api/user', 'api/admin', 'admin/users', 'admin/user'
                ]
                f.write('\n'.join(user_paths))
            
            cmd = [
                "gobuster", "dir",
                "-u", target,
                "-w", temp_dict,
                "-t", "5",
                "-x", "php,html,js,txt,json,xml,asp,aspx,jsp",
                "-o", "/tmp/gobuster_temp.txt",
                "-r", "-q", "-e"
            ]
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            
            unauthorized_paths = []
            if result.returncode == 0:
                lines = result.stdout.split('\n')
                for line in lines:
                    if 'Status:' in line and ('200' in line or '403' in line):
                        parts = line.split()
                        if len(parts) > 0:
                            unauthorized_paths.append(parts[0])
            
            # 清理临时文件
            if os.path.exists(temp_dict):
                os.remove(temp_dict)
            
            return {
                'success': result.returncode == 0,
                'output': result.stdout,
                'unauthorized_paths': unauthorized_paths,
                'error': result.stderr if result.returncode != 0 else None
            }
        except subprocess.TimeoutExpired:
            return {
                'success': False,
                'output': '',
                'unauthorized_paths': [],
                'error': 'Gobuster扫描超时'
            }
        except Exception as e:
            return {
                'success': False,
                'output': '',
                'unauthorized_paths': [],
                'error': str(e)
            }
    
    def _run_sqlmap(self, target: str) -> Dict:
        """运行Sqlmap扫描（仅检测权限相关参数）"""
        try:
            # 检测URL参数
            parsed = urlparse(target)
            if parsed.query:
                # 检查是否可能有权限相关参数
                params = parse_qs(parsed.query)
                for param in params:
                    if any(keyword in param.lower() for keyword in ['id', 'user', 'role', 'perm', 'level']):
                        return {
                            'success': True,
                            'output': f'发现可能的权限相关参数: {param}',
                            'parameter': param,
                            'error': None
                        }
            
            return {
                'success': True,
                'output': '未发现权限相关参数',
                'parameter': None,
                'error': None
            }
        except Exception as e:
            return {
                'success': False,
                'output': '',
                'parameter': None,
                'error': str(e)
            }
    
    def _run_nmap(self, target: str) -> Dict:
        """运行Nmap扫描"""
        try:
            # 解析目标IP
            host = urlparse(target).hostname or target
            
            cmd = [
                "nmap",
                "-p", "21,22,23,25,53,80,110,111,135,139,143,443,445,993,995,1723,3306,3389,5900,8080,8443",
                host,
                "-oN", "/tmp/nmap_temp.txt"
            ]
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            
            open_ports = []
            if result.returncode == 0:
                lines = result.stdout.split('\n')
                for line in lines:
                    if '/tcp' in line and 'open' in line:
                        port_match = re.search(r'(\d+)/tcp', line)
                        if port_match:
                            open_ports.append(int(port_match.group(1)))
            
            return {
                'success': result.returncode == 0,
                'output': result.stdout,
                'open_ports': open_ports,
                'error': result.stderr if result.returncode != 0 else None
            }
        except subprocess.TimeoutExpired:
            return {
                'success': False,
                'output': '',
                'open_ports': [],
                'error': 'Nmap扫描超时'
            }
        except Exception as e:
            return {
                'success': False,
                'output': '',
                'open_ports': [],
                'error': str(e)
            }
    
    def _run_whatweb(self, target: str) -> Dict:
        """运行Whatweb扫描"""
        try:
            cmd = [
                "whatweb",
                target,
                "--log-verbose", "/tmp/whatweb_temp.txt"
            ]
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
            
            technologies = []
            if result.returncode == 0:
                # 解析技术栈信息
                lines = result.stdout.split('\n')
                for line in lines:
                    if '[' in line and ']' in line:
                        # 提取技术栈
                        tech_match = re.findall(r'\[([^\]]+)\]', line)
                        technologies.extend(tech_match)
            
            return {
                'success': result.returncode == 0,
                'output': result.stdout,
                'technologies': list(set(technologies)),
                'error': result.stderr if result.returncode != 0 else None
            }
        except subprocess.TimeoutExpired:
            return {
                'success': False,
                'output': '',
                'technologies': [],
                'error': 'Whatweb扫描超时'
            }
        except Exception as e:
            return {
                'success': False,
                'output': '',
                'technologies': [],
                'error': str(e)
            }

class AdvancedAuthHandler:
    """高级认证处理器"""
    def __init__(self, session: requests.Session):
        self.session = session
        self.auth_methods = {
            'jwt': self._handle_jwt,
            'oauth': self._handle_oauth,
            'api_key': self._handle_api_key,
            'session': self._handle_session,
            'basic': self._handle_basic
        }
    
    def _handle_jwt(self, token: str) -> Dict:
        """处理JWT令牌"""
        try:
            # 解码JWT令牌（不验证签名以进行测试）
            decoded = jwt.decode(token, options={"verify_signature": False})
            return {
                'type': 'jwt',
                'payload': decoded,
                'raw_token': token,
                'is_valid': True
            }
        except Exception:
            return {
                'type': 'jwt',
                'is_valid': False
            }
    
    def _handle_oauth(self, token: str) -> Dict:
        """处理OAuth令牌"""
        return {
            'type': 'oauth',
            'token': token,
            'is_valid': True
        }
    
    def _handle_api_key(self, key: str) -> Dict:
        """处理API密钥"""
        return {
            'type': 'api_key',
            'key': key,
            'is_valid': True
        }
    
    def _handle_session(self, session_id: str) -> Dict:
        """处理会话ID"""
        return {
            'type': 'session',
            'session_id': session_id,
            'is_valid': True
        }
    
    def _handle_basic(self, credentials: str) -> Dict:
        """处理基本认证"""
        return {
            'type': 'basic',
            'credentials': credentials,
            'is_valid': True
        }
    
    def extract_auth_info(self, response: requests.Response) -> Dict:
        """从响应中提取认证信息"""
        auth_info = {}
        
        # 检查Authorization头
        auth_header = response.headers.get('Authorization', '')
        if auth_header:
            if 'Bearer' in auth_header:
                token = auth_header.replace('Bearer ', '').strip()
                auth_info['jwt'] = self._handle_jwt(token)
            elif 'Basic' in auth_header:
                auth_info['basic'] = self._handle_basic(auth_header)
        
        # 检查Set-Cookie头
        cookies = dict(response.cookies)
        for name, value in cookies.items():
            if 'auth' in name.lower() or 'session' in name.lower() or 'token' in name.lower():
                if 'jwt' in name.lower():
                    auth_info['jwt'] = self._handle_jwt(value)
                elif 'session' in name.lower():
                    auth_info['session'] = self._handle_session(value)
                elif 'api' in name.lower():
                    auth_info['api_key'] = self._handle_api_key(value)
        
        return auth_info

class BusinessLogicDetector:
    """业务逻辑检测器"""
    def __init__(self, session: requests.Session):
        self.session = session
        self.detected_workflows = []
    
    def detect_multi_step_workflow(self, base_url: str) -> List[Dict]:
        """检测多步骤业务流程"""
        workflows = []
        
        # 检测常见的多步骤流程
        common_workflows = [
            # 购物车到支付
            {
                'name': '购物车支付流程',
                'steps': ['/cart', '/checkout', '/payment', '/confirm'],
                'required_data': ['cart_id', 'user_id', 'payment_method']
            },
            # 用户注册流程
            {
                'name': '用户注册流程',
                'steps': ['/register', '/verify', '/activate', '/login'],
                'required_data': ['email', 'verification_code', 'password']
            },
            # 订单处理流程
            {
                'name': '订单处理流程',
                'steps': ['/order', '/process', '/ship', '/complete'],
                'required_data': ['order_id', 'status', 'user_id']
            }
        ]
        
        for workflow in common_workflows:
            try:
                detected_steps = []
                for step in workflow['steps']:
                    url = urljoin(base_url, step)
                    try:
                        response = self.session.get(url, timeout=5)
                        if response.status_code in [200, 201, 401, 403]:
                            detected_steps.append({
                                'step': step,
                                'url': url,
                                'status': response.status_code
                            })
                    except:
                        continue
                
                if len(detected_steps) >= 2:  # 至少2个步骤
                    workflows.append({
                        'name': workflow['name'],
                        'detected_steps': detected_steps,
                        'required_data': workflow['required_data']
                    })
            except Exception:
                continue
        
        return workflows
    
    def detect_state_machine_bypass(self, endpoints: List[Dict]) -> List[Dict]:
        """检测状态机绕过漏洞"""
        bypass_vulns = []
        
        # 检查可能的状态机绕过
        state_indicators = [
            'pending', 'approved', 'rejected', 'active', 'inactive',
            'draft', 'published', 'archived', 'deleted'
        ]
        
        for endpoint in endpoints:
            try:
                response = self.session.get(endpoint['url'], timeout=5)
                content = response.text.lower()
                
                # 检查是否包含状态相关关键词
                for state in state_indicators:
                    if state in content:
                        # 尝试直接修改状态参数
                        bypass_tests = self._test_state_bypass(endpoint['url'], state)
                        bypass_vulns.extend(bypass_tests)
            except:
                continue
        
        return bypass_vulns
    
    def _test_state_bypass(self, url: str, current_state: str) -> List[Dict]:
        """测试状态绕过"""
        bypass_vulns = []
        
        # 尝试直接修改状态参数
        state_bypass_attempts = [
            # 尝试提升权限状态
            {'status': 'admin', 'role': 'admin', 'level': '99'},
            {'status': 'active', 'role': 'admin', 'level': '10'},
            {'status': 'approved', 'role': 'moderator', 'level': '5'},
            # 尝试绕过限制状态
            {'status': 'active', 'bypass_limit': 'true'},
            {'status': 'unrestricted', 'role': 'superuser'}
        ]
        
        for attempt in state_bypass_attempts:
            try:
                # 尝试POST请求修改状态
                response = self.session.post(url, data=attempt, timeout=5)
                
                if response.status_code in [200, 201, 204]:
                    bypass_vulns.append({
                        'vulnerable_url': url,
                        'attempted_state': attempt,
                        'response_status': response.status_code,
                        'vulnerability_type': 'state_machine_bypass',
                        'description': f'可能绕过状态限制: {current_state} -> {attempt}'
                    })
            except:
                continue
        
        return bypass_vulns

class AdvancedParameterTester:
    """高级参数测试器"""
    def __init__(self):
        self.uuid_patterns = [
            r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',
            r'[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}'
        ]
        self.guid_patterns = [
            r'\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}',
            r'\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}'
        ]
    
    def generate_advanced_test_values(self) -> List[str]:
        """生成高级测试值"""
        test_values = []
        
        # UUID/GUID测试值
        for _ in range(5):
            test_values.append(str(uuid.uuid4()))
            test_values.append(str(uuid.uuid1()))
        
        # 特殊字符测试值
        special_chars = [
            'admin', 'root', 'user', 'guest',
            '0', '-1', '999999', 'null', 'undefined',
            '../', './', '%2e%2e%2f', '%2e%2e%2f%2e%2e%2f',
            '1\' OR \'1\'=\'1', '1" OR "1"="1',
            '<script>alert(1)</script>', 'javascript:alert(1)'
        ]
        test_values.extend(special_chars)
        
        # 时间戳相关
        now = datetime.now()
        test_values.extend([
            str(int(now.timestamp())),
            str(int(now.timestamp() - 86400)),  # 24小时前
            str(int(now.timestamp() + 86400)),  # 24小时后
            now.strftime('%Y%m%d'),
            now.strftime('%Y-%m-%d'),
            now.strftime('%H:%M:%S')
        ])
        
        # 随机生成的测试值
        for _ in range(10):
            length = random.randint(8, 32)
            test_values.append(''.join(random.choices(
                string.ascii_letters + string.digits + '-_', k=length
            )))
        
        return test_values
    
    def detect_object_references(self, content: str) -> List[Dict]:
        """检测对象引用"""
        references = []
        
        # 检测UUID模式
        for pattern in self.uuid_patterns:
            matches = re.findall(pattern, content, re.IGNORECASE)
            for match in matches:
                references.append({
                    'type': 'uuid',
                    'value': match,
                    'pattern': pattern
                })
        
        # 检测GUID模式
        for pattern in self.guid_patterns:
            matches = re.findall(pattern, content, re.IGNORECASE)
            for match in matches:
                references.append({
                    'type': 'guid',
                    'value': match,
                    'pattern': pattern
                })
        
        # 检测数字ID模式
        id_patterns = [
            r'(?<=id=|/)\d{3,10}(?=/|&|$)',  # URL中的ID
            r'(?<=user_|profile_|order_)\d{3,10}',  # 前缀+数字
        ]
        
        for pattern in id_patterns:
            matches = re.findall(pattern, content)
            for match in matches:
                references.append({
                    'type': 'numeric_id',
                    'value': match,
                    'pattern': pattern
                })
        
        return references

class ProgressTracker:
    """进度跟踪器"""
    def __init__(self, total_steps):
        self.total_steps = total_steps
        self.current_step = 0
        self.start_time = time.time()
        self.lock = threading.Lock()
    
    def update(self, step_name, current=0, total=0):
        """更新进度"""
        with self.lock:
            self.current_step += 1
            elapsed = time.time() - self.start_time
            progress = min(100.0, (self.current_step / self.total_steps) * 100)
            
            if total > 0:
                print(f"\r[进度: {progress:.1f}%] {step_name} ({current}/{total}) - 耗时: {elapsed:.1f}s", end='', flush=True)
            else:
                print(f"\r[进度: {progress:.1f}%] {step_name} - 耗时: {elapsed:.1f}s", end='', flush=True)

class Kali2025PermissionBypassTester:
    def __init__(self, base_url, threads=10):
        """
        初始化Kali 2025权限绕过检测器
        :param base_url: 目标URL
        :param threads: 并发线程数
        """
        self.base_url = base_url
        self.threads = threads
        self.parsed_url = urlparse(base_url)
        self.host = self.parsed_url.hostname
        self.port = self.parsed_url.port or (443 if self.parsed_url.scheme == 'https' else 80)
        self.scheme = self.parsed_url.scheme
        self.session = requests.Session()
        self.session.verify = False
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        })
        self.results = {
            'vertical_privilege_escalation': [],
            'horizontal_privilege_escalation': [],
            'authentication_bypass': [],
            'business_logic_vulnerabilities': [],
            'parameter_manipulation': [],
            'session_fixation': [],
            'race_condition': [],
            'kali_tool_results': {},
            'vulnerability_summary': {},
            'recommendations': [],
            'scan_timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        self.progress = ProgressTracker(10)  # 总共10个步骤
        self.report_dir = f"kali2025_permission_bypass_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        self.interrupted = False
        self.kali_tools = KaliToolIntegrator()
        self.auth_handler = AdvancedAuthHandler(self.session)
        self.business_logic_detector = BusinessLogicDetector(self.session)
        self.parameter_tester = AdvancedParameterTester()
        self.create_report_directory()
        
        # 设置信号处理
        signal.signal(signal.SIGINT, self.signal_handler)

    def signal_handler(self, signum, frame):
        """信号处理函数"""
        print(f"\n\n[!] 检测被用户中断...")
        self.interrupted = True
        print("[*] 正在保存当前结果...")
        sys.exit(0)

    def create_report_directory(self):
        """创建报告目录"""
        Path(self.report_dir).mkdir(exist_ok=True)
        print(f"[*] 报告目录已创建: {self.report_dir}")

    def test_connectivity(self):
        """测试目标连通性"""
        print(f"[*] 测试目标连通性: {self.base_url}")
        
        try:
            response = self.session.get(self.base_url, timeout=10)
            print(f"[+] 目标可访问，状态码: {response.status_code}")
            return True
        except requests.exceptions.ConnectionError:
            print(f"[!] 无法连接到目标: {self.base_url}")
            return False
        except requests.exceptions.Timeout:
            print(f"[!] 连接目标超时: {self.base_url}")
            return False
        except Exception as e:
            print(f"[!] 连接测试失败: {str(e)}")
            return False

    def run_kali_tool_analysis(self):
        """运行Kali工具分析"""
        print(f"\n[*] 运行Kali工具分析...")
        
        kali_results = {}
        
        # 运行Nikto
        print(f"    [+] 运行Nikto...")
        nikto_result = self.kali_tools._run_nikto(self.host)
        nikto_result['tool'] = 'nikto'
        kali_results['nikto'] = nikto_result
        self.progress.update("运行Nikto")
        
        # 运行Dirb
        print(f"    [+] 运行Dirb...")
        dirb_result = self.kali_tools._run_dirb(self.base_url)
        dirb_result['tool'] = 'dirb'
        kali_results['dirb'] = dirb_result
        self.progress.update("运行Dirb")
        
        # 运行Gobuster
        print(f"    [+] 运行Gobuster...")
        gobuster_result = self.kali_tools._run_gobuster(self.base_url)
        gobuster_result['tool'] = 'gobuster'
        kali_results['gobuster'] = gobuster_result
        self.progress.update("运行Gobuster")
        
        # 运行Nmap
        print(f"    [+] 运行Nmap...")
        nmap_result = self.kali_tools._run_nmap(self.base_url)
        nmap_result['tool'] = 'nmap'
        kali_results['nmap'] = nmap_result
        self.progress.update("运行Nmap")
        
        # 运行Whatweb
        print(f"    [+] 运行Whatweb...")
        whatweb_result = self.kali_tools._run_whatweb(self.base_url)
        whatweb_result['tool'] = 'whatweb'
        kali_results['whatweb'] = whatweb_result
        self.progress.update("运行Whatweb")
        
        # 分析Kali工具结果，提取权限相关发现
        permission_related_findings = self._analyze_kali_results(kali_results)
        
        self.results['kali_tool_results'] = kali_results
        self.results['permission_related_findings'] = permission_related_findings
        
        print(f"    [-] Kali工具分析完成，发现 {len(permission_related_findings)} 个权限相关问题")
        return permission_related_findings

    def _analyze_kali_results(self, kali_results: Dict) -> List[Dict]:
        """分析Kali工具结果，提取权限相关发现"""
        findings = []
        
        # 分析Nikto结果
        nikto_result = kali_results.get('nikto', {})
        if nikto_result.get('success'):
            vulnerabilities = nikto_result.get('vulnerabilities', [])
            for vuln in vulnerabilities:
                if any(keyword in vuln.lower() for keyword in ['unauthorized', 'admin', 'privilege', 'access']):
                    findings.append({
                        'tool': 'nikto',
                        'type': 'unauthorized_access',
                        'description': vuln,
                        'severity': 'medium'
                    })
        
        # 分析Dirb结果
        dirb_result = kali_results.get('dirb', {})
        if dirb_result.get('success'):
            unauthorized_paths = dirb_result.get('unauthorized_paths', [])
            for path in unauthorized_paths:
                if any(keyword in path.lower() for keyword in ['admin', 'user', 'api', 'profile']):
                    findings.append({
                        'tool': 'dirb',
                        'type': 'unauthorized_path',
                        'description': f'未授权访问路径: {path}',
                        'severity': 'high'
                    })
        
        # 分析Gobuster结果
        gobuster_result = kali_results.get('gobuster', {})
        if gobuster_result.get('success'):
            unauthorized_paths = gobuster_result.get('unauthorized_paths', [])
            for path in unauthorized_paths:
                if any(keyword in path.lower() for keyword in ['admin', 'user', 'api', 'profile']):
                    findings.append({
                        'tool': 'gobuster',
                        'type': 'unauthorized_path',
                        'description': f'未授权访问路径: {path}',
                        'severity': 'high'
                    })
        
        # 分析Nmap结果
        nmap_result = kali_results.get('nmap', {})
        if nmap_result.get('success'):
            open_ports = nmap_result.get('open_ports', [])
            for port in open_ports:
                if port in [22, 23, 3306, 5432, 6379]:  # 常见管理端口
                    findings.append({
                        'tool': 'nmap',
                        'type': 'open_management_port',
                        'description': f'开放管理端口: {port}',
                        'severity': 'medium'
                    })
        
        # 分析Whatweb结果
        whatweb_result = kali_results.get('whatweb', {})
        if whatweb_result.get('success'):
            technologies = whatweb_result.get('technologies', [])
            for tech in technologies:
                if 'admin' in tech.lower() or 'cms' in tech.lower():
                    findings.append({
                        'tool': 'whatweb',
                        'type': 'technology_info',
                        'description': f'检测到技术栈: {tech}',
                        'severity': 'info'
                    })
        
        return findings

    def detect_auth_mechanism(self):
        """检测认证机制"""
        print(f"[*] 检测认证机制...")
        
        try:
            response = self.session.get(self.base_url, timeout=10)
            auth_info = self.auth_handler.extract_auth_info(response)
            
            print(f"    - 检测到认证类型: {list(auth_info.keys())}")
            return auth_info
        except Exception as e:
            print(f"[!] 认证机制检测失败: {str(e)}")
            return {}

    def detect_user_endpoints(self):
        """检测用户相关端点"""
        print(f"[*] 检测用户相关端点...")
        
        # 扩展的用户相关端点
        user_endpoints = [
            # 用户管理
            "/users", "/users/", "/user", "/user/",
            "/admin/users", "/admin/users/", "/admin/user", "/admin/user/",
            "/api/users", "/api/users/", "/api/user", "/api/user/",
            "/api/v1/users", "/api/v2/users", "/api/v3/users",
            
            # 个人信息
            "/profile", "/profile/", "/account", "/account/",
            "/settings", "/settings/", "/dashboard", "/dashboard/",
            "/me", "/me/", "/self", "/self/",
            
            # 权限相关
            "/admin", "/admin/", "/manager", "/manager/",
            "/api/admin", "/api/admin/", "/api/manager", "/api/manager/",
            "/api/v1/admin", "/api/v2/admin",
            
            # ID参数相关
            "/user/1", "/user/2", "/user/3", "/user/999999",
            "/profile/1", "/profile/2", "/profile/3", "/profile/999999",
            "/api/user/1", "/api/user/2", "/api/user/3", "/api/user/999999",
            "/api/profile/1", "/api/profile/2", "/api/profile/999999",
            
            # UUID/GUID相关
            f"/user/{uuid.uuid4()}", f"/profile/{uuid.uuid4()}",
            f"/api/user/{uuid.uuid4()}", f"/api/profile/{uuid.uuid4()}",
            
            # 批量操作
            "/users/batch", "/api/users/batch", "/batch/users",
            "/profiles/batch", "/api/profiles/batch", "/batch/profiles",
            
            # 搜索和过滤
            "/users/search", "/api/users/search", "/search/users",
            "/users/filter", "/api/users/filter", "/filter/users"
        ]
        
        detected_endpoints = []
        
        def check_endpoint(endpoint):
            if self.interrupted:
                return None
            try:
                full_url = urljoin(self.base_url, endpoint)
                response = self.session.get(full_url, timeout=10)
                
                if response.status_code in [200, 201, 202, 203, 204, 205, 206, 401, 403, 404]:
                    content = response.text.lower()
                    
                    user_indicators = [
                        'user', 'profile', 'account', 'dashboard', 'admin',
                        'setting', 'permission', 'role', 'privilege', 'id',
                        'email', 'name', 'username', 'password', 'token'
                    ]
                    
                    has_user_info = any(indicator in content for indicator in user_indicators)
                    
                    return {
                        'url': full_url,
                        'status_code': response.status_code,
                        'has_user_info': has_user_info,
                        'response_length': len(response.text),
                        'content_type': response.headers.get('Content-Type', '')
                    }
                return None
            except Exception:
                return None
        
        with ThreadPoolExecutor(max_workers=self.threads) as executor:
            futures = [executor.submit(check_endpoint, endpoint) for endpoint in user_endpoints]
            
            completed = 0
            total_endpoints = len(user_endpoints)
            
            for future in as_completed(futures):
                if self.interrupted:
                    for f in futures:
                        f.cancel()
                    break
                
                completed += 1
                self.progress.update("检测用户端点", completed, total_endpoints)
                
                result = future.result()
                if result:
                    detected_endpoints.append(result)
        
        print(f"    - 发现 {len(detected_endpoints)} 个用户相关端点")
        return detected_endpoints

    def test_authentication_bypass(self, user_endpoints):
        """测试认证绕过"""
        print(f"\n[*] 测试认证绕过...")
        
        bypass_vulns = []
        
        # 测试各种认证绕过技术
        bypass_techniques = [
            # JWT绕过
            {
                'name': 'JWT空密钥绕过',
                'headers': {'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'},
                'cookies': {},
                'description': '使用空密钥签名的JWT'
            },
            {
                'name': 'JWT算法混淆',
                'headers': {'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTUxNjIzOTAyMn0.invalid_signature'},
                'cookies': {},
                'description': '使用不安全算法的JWT'
            },
            # API密钥绕过
            {
                'name': '默认API密钥',
                'headers': {'X-API-Key': 'admin', 'Authorization': 'Bearer admin'},
                'cookies': {},
                'description': '使用默认API密钥'
            },
            # HTTP头绕过
            {
                'name': 'X-Forwarded-User绕过',
                'headers': {'X-Forwarded-User': 'admin', 'X-Original-User': 'admin'},
                'cookies': {},
                'description': '通过X-Forwarded-User头绕过认证'
            },
            {
                'name': 'X-Real-IP绕过',
                'headers': {'X-Real-IP': '127.0.0.1', 'X-Forwarded-For': '127.0.0.1'},
                'cookies': {},
                'description': '通过IP伪造绕过认证'
            }
        ]
        
        def test_bypass_technique(technique):
            if self.interrupted:
                return None
            try:
                # 尝试访问管理端点
                admin_endpoints = [ep for ep in user_endpoints if 'admin' in ep['url'].lower()]
                
                for endpoint in admin_endpoints:
                    headers = {**self.session.headers, **technique['headers']}
                    
                    response = self.session.get(
                        endpoint['url'], 
                        headers=headers, 
                        cookies=technique['cookies'],
                        timeout=10
                    )
                    
                    # 检查是否成功绕过认证
                    if response.status_code in [200, 201, 202]:
                        content = response.text.lower()
                        
                        # 检查是否包含管理功能
                        admin_indicators = [
                            'admin', 'dashboard', 'control', 'manage', 'delete',
                            'user_list', 'permission', 'role', 'system'
                        ]
                        
                        has_admin_info = any(indicator in content for indicator in admin_indicators)
                        
                        if has_admin_info:
                            return {
                                'vulnerable_url': endpoint['url'],
                                'bypass_technique': technique['name'],
                                'status_code': response.status_code,
                                'vulnerability_type': 'authentication_bypass',
                                'severity': 'critical',
                                'description': f'{technique["description"]} - 成功访问管理功能'
                            }
                
                return None
            except Exception:
                return None
        
        with ThreadPoolExecutor(max_workers=5) as executor:  # 限制并发数
            futures = [executor.submit(test_bypass_technique, technique) for technique in bypass_techniques]
            
            completed = 0
            total_techniques = len(bypass_techniques)
            
            for future in as_completed(futures):
                if self.interrupted:
                    for f in futures:
                        f.cancel()
                    break
                
                completed += 1
                self.progress.update("测试认证绕过", completed, total_techniques)
                
                result = future.result()
                if result:
                    bypass_vulns.append(result)
                    print(f"\n    [!] 发现认证绕过: {result['bypass_technique']} -> {result['vulnerable_url']}")
        
        print()  # 换行
        return bypass_vulns

    def test_vertical_privilege_escalation(self, user_endpoints):
        """测试垂直权限提升"""
        print(f"\n[*] 测试垂直权限提升...")
        
        vertical_vulns = []
        
        # 扩展的高权限指示器
        high_privilege_indicators = [
            'admin', 'administrator', 'manager', 'moderator', 'root',
            'superuser', 'system', 'control', 'manage', 'delete', 'remove',
            'create', 'update', 'config', 'settings', 'users', 'permissions',
            'roles', 'system', 'database', 'backup', 'restore', 'export',
            'import', 'install', 'uninstall', 'activate', 'deactivate'
        ]
        
        def test_endpoint_privilege(endpoint):
            if self.interrupted:
                return None
            try:
                response = self.session.get(endpoint['url'], timeout=10)
                
                content = response.text.lower()
                
                has_high_privilege_indicators = any(
                    indicator in content for indicator in high_privilege_indicators
                )
                
                # 检查是否能够访问高权限功能
                if response.status_code == 200 and has_high_privilege_indicators:
                    return {
                        'vulnerable_url': endpoint['url'],
                        'status_code': response.status_code,
                        'vulnerability_type': 'vertical_privilege_escalation',
                        'severity': 'high',
                        'description': '低权限用户可以访问高权限功能'
                    }
                
                # 检查响应内容中是否包含敏感信息
                sensitive_keywords = [
                    'password', 'token', 'secret', 'key', 'admin', 'root',
                    'system', 'config', 'database', 'user_list', 'permission',
                    'email', 'phone', 'address', 'ssn', 'credit_card', 'bank'
                ]
                
                has_sensitive_info = any(keyword in content for keyword in sensitive_keywords)
                
                if response.status_code == 200 and has_sensitive_info and any(admin_word in endpoint['url'].lower() for admin_word in ['admin', 'manage', 'control']):
                    return {
                        'vulnerable_url': endpoint['url'],
                        'status_code': response.status_code,
                        'vulnerability_type': 'vertical_privilege_escalation',
                        'severity': 'medium',
                        'description': '访问管理端点返回敏感信息'
                    }
                
                return None
            except Exception:
                return None
        
        with ThreadPoolExecutor(max_workers=self.threads) as executor:
            futures = [executor.submit(test_endpoint_privilege, endpoint) for endpoint in user_endpoints]
            
            completed = 0
            total_endpoints = len(user_endpoints)
            
            for future in as_completed(futures):
                if self.interrupted:
                    for f in futures:
                        f.cancel()
                    break
                
                completed += 1
                self.progress.update("测试垂直权限", completed, total_endpoints)
                
                result = future.result()
                if result:
                    vertical_vulns.append(result)
                    print(f"\n    [!] 发现垂直越权: {result['vulnerable_url']} - {result['description']}")
        
        print()  # 换行
        return vertical_vulns

    def test_horizontal_privilege_escalation(self, user_endpoints):
        """测试水平权限提升"""
        print(f"\n[*] 测试水平权限提升...")
        
        horizontal_vulns = []
        
        # 寻找包含用户ID的端点
        user_id_endpoints = []
        for ep in user_endpoints:
            if any(pattern in ep['url'] for pattern in [r'/\d+', r'/user/\d+', r'/profile/\d+', r'/api/user/\d+']):
                user_id_endpoints.append(ep)
        
        if not user_id_endpoints:
            print("    [-] 未发现包含用户ID的端点，跳过水平越权测试")
            return horizontal_vulns
        
        # 生成测试用户ID（包括UUID和数字ID）
        test_ids = []
        
        # 数字ID测试
        test_ids.extend([str(i) for i in range(1, 21)])  # 1-20
        
        # UUID测试
        for _ in range(10):
            test_ids.append(str(uuid.uuid4()))
        
        # 特殊测试值
        test_ids.extend(['admin', 'root', 'user', 'test', 'guest'])
        
        def test_user_access(endpoint_url, user_id):
            if self.interrupted:
                return None
            try:
                # 智能替换URL中的用户ID
                test_url = endpoint_url
                
                # 替换数字ID
                test_url = re.sub(r'/\d+', f'/{user_id}', test_url)
                test_url = re.sub(r'/user/\d+', f'/user/{user_id}', test_url)
                test_url = re.sub(r'/profile/\d+', f'/profile/{user_id}', test_url)
                test_url = re.sub(r'/api/user/\d+', f'/api/user/{user_id}', test_url)
                
                # 如果是UUID格式，也尝试替换
                uuid_pattern = r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
                test_url = re.sub(uuid_pattern, user_id, test_url, flags=re.IGNORECASE)
                
                response = self.session.get(test_url, timeout=10)
                
                # 检查是否能访问其他用户的数据
                if response.status_code == 200:
                    content = response.text.lower()
                    
                    # 检查响应中是否包含用户相关信息
                    user_related_keywords = [
                        'user', 'profile', 'email', 'phone', 'address', 'name',
                        'username', 'account', 'info', 'data', 'details', 'personal',
                        'private', 'secret', 'password', 'token', 'session'
                    ]
                    
                    has_user_info = any(keyword in content for keyword in user_related_keywords)
                    
                    if has_user_info:
                        return {
                            'vulnerable_url': test_url,
                            'target_user_id': user_id,
                            'status_code': response.status_code,
                            'vulnerability_type': 'horizontal_privilege_escalation',
                            'severity': 'medium',
                            'description': f'可以访问用户 {user_id} 的信息'
                        }
                
                return None
            except Exception:
                return None
        
        with ThreadPoolExecutor(max_workers=self.threads) as executor:
            futures = []
            for endpoint in user_id_endpoints:
                for user_id in test_ids:
                    futures.append(executor.submit(test_user_access, endpoint['url'], user_id))
            
            completed = 0
            total_tests = len(futures)
            
            for future in as_completed(futures):
                if self.interrupted:
                    for f in futures:
                        f.cancel()
                    break
                
                completed += 1
                self.progress.update("测试水平权限", completed, total_tests)
                
                result = future.result()
                if result:
                    horizontal_vulns.append(result)
                    print(f"\n    [!] 发现水平越权: {result['vulnerable_url']} - {result['description']}")
        
        print()  # 换行
        return horizontal_vulns

    def test_parameter_manipulation(self):
        """测试参数篡改漏洞"""
        print(f"\n[*] 测试参数篡改漏洞...")
        
        parameter_vulns = []
        
        # 扩展的参数篡改测试场景
        test_scenarios = [
            # ID参数篡改
            {
                'base_url': urljoin(self.base_url, '/api/user/1'),
                'param': 'user_id',
                'values': self.parameter_tester.generate_advanced_test_values(),
                'description': '用户ID参数篡改'
            },
            {
                'base_url': urljoin(self.base_url, '/api/profile/1'),
                'param': 'profile_id',
                'values': self.parameter_tester.generate_advanced_test_values(),
                'description': '个人资料ID参数篡改'
            },
            {
                'base_url': urljoin(self.base_url, '/api/order/1'),
                'param': 'order_id',
                'values': self.parameter_tester.generate_advanced_test_values(),
                'description': '订单ID参数篡改'
            },
            {
                'base_url': urljoin(self.base_url, '/api/file/1'),
                'param': 'file_id',
                'values': self.parameter_tester.generate_advanced_test_values(),
                'description': '文件ID参数篡改'
            }
        ]
        
        def test_parameter_scenario(scenario):
            if self.interrupted:
                return None
            try:
                vulns_found = []
                
                for value in scenario['values'][:50]:  # 限制测试数量
                    if self.interrupted:
                        break
                    
                    # 构造测试URL
                    test_url = scenario['base_url']
                    if '?' in test_url:
                        test_url += f"&{scenario['param']}={value}"
                    else:
                        test_url += f"?{scenario['param']}={value}"
                    
                    try:
                        response = self.session.get(test_url, timeout=10)
                        
                        # 检查是否成功访问其他用户的数据
                        if response.status_code == 200:
                            content = response.text.lower()
                            
                            user_related_keywords = [
                                'user', 'profile', 'email', 'phone', 'address', 'name',
                                'username', 'account', 'info', 'data', 'details', 'personal'
                            ]
                            
                            has_user_info = any(keyword in content for keyword in user_related_keywords)
                            
                            if has_user_info:
                                vuln = {
                                    'vulnerable_url': test_url,
                                    'parameter': scenario['param'],
                                    'manipulated_value': value,
                                    'status_code': response.status_code,
                                    'vulnerability_type': 'parameter_manipulation',
                                    'severity': 'high',
                                    'description': f'{scenario["description"]} - 参数值: {value}'
                                }
                                vulns_found.append(vuln)
                                print(f"\n    [!] 发现参数篡改: {test_url} - {vuln['description']}")
                    
                    except Exception:
                        continue
                
                return vulns_found
            except Exception:
                return None
        
        with ThreadPoolExecutor(max_workers=self.threads) as executor:
            futures = [executor.submit(test_parameter_scenario, scenario) for scenario in test_scenarios]
            
            completed = 0
            total_scenarios = len(test_scenarios)
            
            for future in as_completed(futures):
                if self.interrupted:
                    for f in futures:
                        f.cancel()
                    break
                
                completed += 1
                self.progress.update("测试参数篡改", completed, total_scenarios)
                
                result = future.result()
                if result:
                    parameter_vulns.extend(result)
        
        print()  # 换行
        return parameter_vulns

    def test_business_logic_vulnerabilities(self, user_endpoints):
        """测试业务逻辑漏洞"""
        print(f"\n[*] 测试业务逻辑漏洞...")
        
        business_logic_vulns = []
        
        # 检测多步骤业务流程
        workflows = self.business_logic_detector.detect_multi_step_workflow(self.base_url)
        
        for workflow in workflows:
            print(f"    [+] 发现业务流程: {workflow['name']}")
            
            # 测试流程绕过
            for i, step in enumerate(workflow['detected_steps']):
                try:
                    # 尝试跳过中间步骤
                    for j in range(i + 2, len(workflow['detected_steps'])):  # 跳过至少一个步骤
                        skip_step = workflow['detected_steps'][j]
                        
                        response = self.session.get(skip_step['url'], timeout=10)
                        
                        if response.status_code in [200, 201, 202]:
                            vuln = {
                                'vulnerable_url': skip_step['url'],
                                'workflow_name': workflow['name'],
                                'skipped_steps': [s['step'] for s in workflow['detected_steps'][i+1:j]],
                                'status_code': response.status_code,
                                'vulnerability_type': 'business_logic_bypass',
                                'severity': 'medium',
                                'description': f'业务流程绕过 - 跳过步骤: {workflow["detected_steps"][i+1:j]}'
                            }
                            business_logic_vulns.append(vuln)
                            print(f"\n    [!] 发现业务流程绕过: {vuln['vulnerable_url']} - {vuln['description']}")
                
                except Exception:
                    continue
        
        # 检测状态机绕过
        state_machine_bypasses = self.business_logic_detector.detect_state_machine_bypass(user_endpoints)
        business_logic_vulns.extend(state_machine_bypasses)
        
        print()  # 换行
        return business_logic_vulns

    def test_race_conditions(self):
        """测试竞态条件漏洞"""
        print(f"\n[*] 测试竞态条件漏洞...")
        
        race_condition_vulns = []
        
        # 常见的竞态条件场景
        race_scenarios = [
            # 余额操作
            {
                'url': urljoin(self.base_url, '/api/transfer'),
                'method': 'POST',
                'data': {'from': 'user1', 'to': 'user2', 'amount': 100},
                'description': '资金转账竞态条件'
            },
            # 库存操作
            {
                'url': urljoin(self.base_url, '/api/purchase'),
                'method': 'POST',
                'data': {'product_id': '1', 'quantity': 1},
                'description': '库存购买竞态条件'
            },
            # 订单创建
            {
                'url': urljoin(self.base_url, '/api/order'),
                'method': 'POST',
                'data': {'item': 'limited_item', 'quantity': 1},
                'description': '限量商品订单竞态条件'
            }
        ]
        
        async def test_race_condition_async(scenario, num_requests=10):
            """异步测试竞态条件"""
            async with aiohttp.ClientSession() as session:
                tasks = []
                for i in range(num_requests):
                    if self.interrupted:
                        break
                    task = asyncio.create_task(
                        self._make_request_async(session, scenario)
                    )
                    tasks.append(task)
                    await asyncio.sleep(0.01)  # 小延迟
                
                responses = await asyncio.gather(*tasks, return_exceptions=True)
                
                # 分析响应
                success_count = sum(1 for resp in responses if not isinstance(resp, Exception) and resp.get('status') == 200)
                
                if success_count > 1:
                    return {
                        'vulnerable_url': scenario['url'],
                        'request_count': num_requests,
                        'success_count': success_count,
                        'vulnerability_type': 'race_condition',
                        'severity': 'high',
                        'description': f'{scenario["description"]} - {success_count}个请求成功'
                    }
            
            return None
        
        async def run_race_tests():
            vulns = []
            for scenario in race_scenarios:
                if self.interrupted:
                    break
                try:
                    result = await test_race_condition_async(scenario)
                    if result:
                        vulns.append(result)
                        print(f"\n    [!] 发现竞态条件: {result['vulnerable_url']} - {result['description']}")
                except Exception:
                    continue
            return vulns
        
        try:
            vulns = asyncio.run(run_race_tests())
            race_condition_vulns.extend(vulns)
        except Exception as e:
            print(f"    [!] 竞态条件测试失败: {str(e)}")
        
        print()  # 换行
        return race_condition_vulns

    async def _make_request_async(self, session, scenario):
        """异步发送请求"""
        try:
            if scenario['method'] == 'POST':
                async with session.post(scenario['url'], json=scenario['data'], timeout=5) as response:
                    return {'status': response.status, 'text': await response.text()}
            else:
                async with session.get(scenario['url'], timeout=5) as response:
                    return {'status': response.status, 'text': await response.text()}
        except Exception as e:
            return {'status': 0, 'error': str(e)}

    def test_session_fixation(self):
        """测试会话固定漏洞"""
        print(f"\n[*] 测试会话固定漏洞...")
        
        session_vulns = []
        
        try:
            # 获取初始会话
            initial_response = self.session.get(self.base_url, timeout=10)
            initial_cookies = dict(initial_response.cookies)
            
            # 检查是否存在可预测的会话ID
            for cookie_name, cookie_value in initial_cookies.items():
                if any(name in cookie_name.lower() for name in ['session', 'auth', 'token']):
                    # 检查会话ID是否过于简单或可预测
                    if (len(cookie_value) < 16 or 
                        cookie_value.isdigit() or 
                        len(set(cookie_value)) < 8 or
                        cookie_value.lower() in ['1', 'admin', 'user', 'guest', 'test']):
                        
                        vuln = {
                            'vulnerability_type': 'session_fixation',
                            'severity': 'medium',
                            'description': f'会话ID可预测: {cookie_name}={cookie_value}',
                            'cookie_name': cookie_name,
                            'cookie_value': cookie_value
                        }
                        session_vulns.append(vuln)
                        print(f"\n    [!] 发现会话固定: {vuln['description']}")
        
        except Exception as e:
            print(f"    [!] 会话固定测试失败: {str(e)}")
        
        print()  # 换行
        return session_vulns

    def run_comprehensive_test(self):
        """运行综合测试"""
        print(f"\n[*] 开始综合权限绕过检测: {self.base_url}")
        print("="*60)
        
        # 首先测试连通性
        if not self.test_connectivity():
            print(f"[!] 目标不可达，无法进行扫描")
            return self.results
        
        # 运行Kali工具分析
        kali_findings = self.run_kali_tool_analysis()
        self.progress.update("运行Kali工具分析")
        
        # 检测认证机制
        auth_mechanism = self.detect_auth_mechanism()
        self.progress.update("检测认证机制")
        
        # 检测用户相关端点
        user_endpoints = self.detect_user_endpoints()
        self.progress.update("检测用户端点")
        
        # 测试认证绕过
        auth_bypass_vulns = self.test_authentication_bypass(user_endpoints)
        self.results['authentication_bypass'] = auth_bypass_vulns
        self.progress.update("测试认证绕过")
        
        # 测试垂直权限提升
        vertical_vulns = self.test_vertical_privilege_escalation(user_endpoints)
        self.results['vertical_privilege_escalation'] = vertical_vulns
        self.progress.update("测试垂直权限")
        
        # 测试水平权限提升
        horizontal_vulns = self.test_horizontal_privilege_escalation(user_endpoints)
        self.results['horizontal_privilege_escalation'] = horizontal_vulns
        self.progress.update("测试水平权限")
        
        # 测试参数篡改
        parameter_vulns = self.test_parameter_manipulation()
        self.results['parameter_manipulation'] = parameter_vulns
        self.progress.update("测试参数篡改")
        
        # 测试业务逻辑漏洞
        business_logic_vulns = self.test_business_logic_vulnerabilities(user_endpoints)
        self.results['business_logic_vulnerabilities'] = business_logic_vulns
        self.progress.update("测试业务逻辑")
        
        # 测试竞态条件
        race_condition_vulns = self.test_race_conditions()
        self.results['race_condition'] = race_condition_vulns
        self.progress.update("测试竞态条件")
        
        # 测试会话固定
        session_vulns = self.test_session_fixation()
        self.results['session_fixation'] = session_vulns
        self.progress.update("测试会话固定")
        
        # 汇总结果
        if not self.interrupted:
            self.results['vulnerability_summary'] = self.generate_summary()
            self.results['recommendations'] = self.generate_recommendations()
            self.results['scan_timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
            return self.results
        else:
            print("\n[!] 扫描被中断，返回部分结果...")
            self.results['vulnerability_summary'] = self.generate_summary()
            self.results['recommendations'] = self.generate_recommendations()
            self.results['scan_timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            return self.results

    def generate_summary(self):
        """生成漏洞摘要"""
        summary = {
            'vertical_privilege_escalation': len(self.results.get('vertical_privilege_escalation', [])),
            'horizontal_privilege_escalation': len(self.results.get('horizontal_privilege_escalation', [])),
            'authentication_bypass': len(self.results.get('authentication_bypass', [])),
            'business_logic_vulnerabilities': len(self.results.get('business_logic_vulnerabilities', [])),
            'parameter_manipulation': len(self.results.get('parameter_manipulation', [])),
            'session_fixation': len(self.results.get('session_fixation', [])),
            'race_condition': len(self.results.get('race_condition', [])),
            'kali_tool_vulnerabilities': len(self.results.get('permission_related_findings', [])),
            'total_vulnerabilities': sum([
                len(self.results.get('vertical_privilege_escalation', [])),
                len(self.results.get('horizontal_privilege_escalation', [])),
                len(self.results.get('authentication_bypass', [])),
                len(self.results.get('business_logic_vulnerabilities', [])),
                len(self.results.get('parameter_manipulation', [])),
                len(self.results.get('session_fixation', [])),
                len(self.results.get('race_condition', [])),
                len(self.results.get('permission_related_findings', []))
            ])
        }
        
        return summary

    def generate_recommendations(self):
        """生成安全建议"""
        recommendations = [
            "1. 实施严格的访问控制机制（ACL）",
            "2. 使用基于角色的访问控制（RBAC）",
            "3. 验证用户身份和权限级别",
            "4. 实施最小权限原则",
            "5. 对敏感操作进行二次验证",
            "6. 使用安全的会话管理",
            "7. 实施参数验证和过滤",
            "8. 定期进行安全审计",
            "9. 使用CSRF令牌防止跨站请求伪造",
            "10. 实施适当的错误处理机制",
            "11. 使用防重放攻击机制",
            "12. 实施速率限制和请求频率控制",
            "13. 使用强加密算法保护敏感数据",
            "14. 实施安全的认证和授权流程",
            "15. 定期更新和修补系统漏洞",
            "16. 部署Web应用防火墙（WAF）",
            "17. 实施安全的API设计",
            "18. 使用安全的编码实践",
            "19. 进行安全代码审查",
            "20. 实施安全监控和日志记录"
        ]
        
        return recommendations

    def save_detailed_report(self):
        """保存详细报告到文件"""
        if not os.path.exists(self.report_dir):
            Path(self.report_dir).mkdir(exist_ok=True)
        
        report_file = f"{self.report_dir}/kali2025_permission_bypass_report.json"
        
        # 保存完整的JSON报告
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(self.results, f, indent=2, ensure_ascii=False)
        
        # 生成人类可读的报告
        readable_report = f"{self.report_dir}/kali2025_permission_bypass_report.txt"
        with open(readable_report, 'w', encoding='utf-8') as f:
            f.write("="*60 + "\n")
            f.write("Web应用权限绕过检测详细报告 - Kali 2025版\n")
            f.write("="*60 + "\n")
            f.write(f"目标URL: {self.base_url}\n")
            f.write(f"检测时间: {self.results.get('scan_timestamp', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))}\n")
            f.write(f"报告目录: {self.report_dir}\n")
            f.write(f"中断状态: {'是' if self.interrupted else '否'}\n")
            f.write("\n")
            
            # 摘要信息
            summary = self.results.get('vulnerability_summary', {})
            f.write("漏洞摘要:\n")
            f.write("-" * 40 + "\n")
            f.write(f"垂直权限提升漏洞: {summary.get('vertical_privilege_escalation', 0)}\n")
            f.write(f"水平权限提升漏洞: {summary.get('horizontal_privilege_escalation', 0)}\n")
            f.write(f"认证绕过漏洞: {summary.get('authentication_bypass', 0)}\n")
            f.write(f"业务逻辑漏洞: {summary.get('business_logic_vulnerabilities', 0)}\n")
            f.write(f"参数篡改漏洞: {summary.get('parameter_manipulation', 0)}\n")
            f.write(f"会话固定漏洞: {summary.get('session_fixation', 0)}\n")
            f.write(f"竞态条件漏洞: {summary.get('race_condition', 0)}\n")
            f.write(f"Kali工具发现: {summary.get('kali_tool_vulnerabilities', 0)}\n")
            f.write(f"总漏洞数: {summary.get('total_vulnerabilities', 0)}\n")
            f.write("\n")
            
            # Kali工具结果
            f.write("Kali工具分析结果:\n")
            f.write("-" * 40 + "\n")
            kali_results = self.results.get('kali_tool_results', {})
            for tool, result in kali_results.items():
                f.write(f"\n{tool.upper()} 扫描结果:\n")
                if result.get('success'):
                    f.write(f"  • 扫描成功\n")
                    if tool == 'nikto':
                        vulns = result.get('vulnerabilities', [])
                        f.write(f"  • 发现 {len(vulns)} 个漏洞\n")
                        for vuln in vulns[:3]:  # 显示前3个
                            f.write(f"    - {vuln[:100]}...\n")
                    elif tool in ['dirb', 'gobuster']:
                        paths = result.get('unauthorized_paths', [])
                        f.write(f"  • 发现 {len(paths)} 个路径\n")
                        for path in paths[:5]:  # 显示前5个
                            f.write(f"    - {path}\n")
                    elif tool == 'nmap':
                        ports = result.get('open_ports', [])
                        f.write(f"  • 发现 {len(ports)} 个开放端口\n")
                        f.write(f"    - {ports}\n")
                    elif tool == 'whatweb':
                        techs = result.get('technologies', [])
                        f.write(f"  • 检测到技术栈: {', '.join(techs[:5])}\n")
                else:
                    f.write(f"  • 扫描失败: {result.get('error', '未知错误')}\n")
            
            # 权限相关发现
            permission_findings = self.results.get('permission_related_findings', [])
            if permission_findings:
                f.write(f"\n权限相关发现:\n")
                for finding in permission_findings:
                    f.write(f"  • {finding['description']} ({finding['severity']})\n")
            
            # 详细结果
            f.write("\n详细检测结果:\n")
            f.write("-" * 40 + "\n")
            
            # 垂直权限提升漏洞
            vertical_vulns = self.results.get('vertical_privilege_escalation', [])
            if vertical_vulns:
                f.write("\n垂直权限提升漏洞:\n")
                for vuln in vertical_vulns:
                    f.write(f"  • {vuln['vulnerable_url']} - {vuln['description']} (严重等级: {vuln['severity']})\n")
            
            # 水平权限提升漏洞
            horizontal_vulns = self.results.get('horizontal_privilege_escalation', [])
            if horizontal_vulns:
                f.write("\n水平权限提升漏洞:\n")
                for vuln in horizontal_vulns:
                    f.write(f"  • {vuln['vulnerable_url']} - {vuln['description']} (用户ID: {vuln.get('target_user_id', 'N/A')})\n")
            
            # 认证绕过漏洞
            auth_bypass_vulns = self.results.get('authentication_bypass', [])
            if auth_bypass_vulns:
                f.write("\n认证绕过漏洞:\n")
                for vuln in auth_bypass_vulns:
                    f.write(f"  • {vuln['vulnerable_url']} - {vuln['description']} (绕过技术: {vuln.get('bypass_technique', 'N/A')})\n")
            
            # 业务逻辑漏洞
            business_logic_vulns = self.results.get('business_logic_vulnerabilities', [])
            if business_logic_vulns:
                f.write("\n业务逻辑漏洞:\n")
                for vuln in business_logic_vulns:
                    f.write(f"  • {vuln['vulnerable_url']} - {vuln['description']}\n")
            
            # 参数篡改漏洞
            param_vulns = self.results.get('parameter_manipulation', [])
            if param_vulns:
                f.write("\n参数篡改漏洞:\n")
                for vuln in param_vulns:
                    f.write(f"  • {vuln['vulnerable_url']} - {vuln['description']}\n")
            
            # 会话固定漏洞
            session_vulns = self.results.get('session_fixation', [])
            if session_vulns:
                f.write("\n会话固定漏洞:\n")
                for vuln in session_vulns:
                    f.write(f"  • {vuln['cookie_name']}={vuln['cookie_value']} - {vuln['description']}\n")
            
            # 竞态条件漏洞
            race_vulns = self.results.get('race_condition', [])
            if race_vulns:
                f.write("\n竞态条件漏洞:\n")
                for vuln in race_vulns:
                    f.write(f"  • {vuln['vulnerable_url']} - {vuln['description']}\n")
            
            # 安全建议
            f.write("\n安全建议:\n")
            f.write("-" * 40 + "\n")
            for rec in self.results.get('recommendations', self.generate_recommendations()):
                f.write(f"• {rec}\n")
            
            f.write("="*60 + "\n")
        
        print(f"\n[+] 详细报告已保存至: {self.report_dir}/")
        print(f"    - JSON格式: kali2025_permission_bypass_report.json")
        print(f"    - 文本格式: kali2025_permission_bypass_report.txt")

    def print_summary_report(self):
        """打印摘要报告"""
        print("\n" + "="*60)
        print("Web应用权限绕过检测摘要报告 - Kali 2025版")
        print("="*60)
        print(f"目标URL: {self.base_url}")
        print(f"检测时间: {self.results.get('scan_timestamp', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))}")
        print(f"报告目录: {self.report_dir}")
        print(f"中断状态: {'是' if self.interrupted else '否'}")
        print()
        
        # 摘要信息
        summary = self.results.get('vulnerability_summary', {})
        print("漏洞摘要:")
        print("-" * 40)
        print(f"垂直权限提升漏洞: {summary.get('vertical_privilege_escalation', 0)}")
        print(f"水平权限提升漏洞: {summary.get('horizontal_privilege_escalation', 0)}")
        print(f"认证绕过漏洞: {summary.get('authentication_bypass', 0)}")
        print(f"业务逻辑漏洞: {summary.get('business_logic_vulnerabilities', 0)}")
        print(f"参数篡改漏洞: {summary.get('parameter_manipulation', 0)}")
        print(f"会话固定漏洞: {summary.get('session_fixation', 0)}")
        print(f"竞态条件漏洞: {summary.get('race_condition', 0)}")
        print(f"Kali工具发现: {summary.get('kali_tool_vulnerabilities', 0)}")
        print(f"总漏洞数: {summary.get('total_vulnerabilities', 0)}")
        print()
        
        # 总体评估
        total_vulns = summary.get('total_vulnerabilities', 0)
        
        if total_vulns == 0:
            risk_level = "✅ 低风险 - 未发现权限绕过漏洞"
        elif total_vulns <= 3:
            risk_level = "⚠️  中等风险 - 存在少量权限绕过漏洞"
        elif total_vulns <= 8:
            risk_level = "🚨 高风险 - 存在多个权限绕过漏洞"
        else:
            risk_level = "🔥 严重风险 - 存在大量权限绕过漏洞"
        
        print(f"总体风险评估: {risk_level}")
        print(f"总发现漏洞数: {total_vulns}")
        
        # Kali工具结果摘要
        kali_results = self.results.get('kali_tool_results', {})
        print(f"\nKali工具扫描结果:")
        print("-" * 40)
        for tool, result in kali_results.items():
            status = "✅ 成功" if result.get('success') else "❌ 失败"
            print(f"{tool.upper()}: {status}")
        
        if self.interrupted:
            print("⚠️  检测被中断 - 结果可能不完整")
        
        print("="*60)

def get_optimal_threads():
    """获取最优并发数"""
    try:
        import os
        import psutil
        
        # 获取系统信息
        cpu_count = os.cpu_count()
        memory_gb = psutil.virtual_memory().total / (1024**3)
        
        # 基于CPU和内存计算最优并发数
        optimal = min(
            cpu_count * 2,  # CPU核心数的2倍
            int(memory_gb * 8),  # 内存GB数 * 8
            25  # 上限25
        )
        
        return max(5, optimal)  # 至少5个，最多optimal个
    except:
        return 10  # 默认10个

def main():
    """主函数"""
    print("""
    ===========================================
    |  Web应用权限绕过检测工具 v3.0           |
    |  Kali 2025版 - 结合多种安全工具          |
    ===========================================
    """)
    
    print("⚠️  警告: 此工具仅用于授权安全测试!")
    print("请确保您有权限测试目标系统\n")
    
    base_url = input("[+] 请输入目标URL (如: https://example.com): ").strip()
    
    if not base_url.startswith(('http://', 'https://')):
        base_url = 'https://' + base_url
    
    # 自动计算最优并发数
    try:
        optimal_threads = get_optimal_threads()
        
        print(f"[*] 检测到CPU核心数: {os.cpu_count()}")
        print(f"[*] 检测到内存大小: {psutil.virtual_memory().total / (1024**3):.1f}GB")
        print(f"[*] 推荐并发线程数: {optimal_threads}")
        
        threads_input = input(f"[+] 请输入并发线程数 (默认{optimal_threads}, 最大30): ").strip()
        if threads_input:
            threads = min(int(threads_input), 30)
        else:
            threads = optimal_threads
    except:
        # 如果无法获取系统信息，使用默认值
        threads = 10
    
    print(f"\n[*] 开始检测...")
    print(f"[*] 目标: {base_url}")
    print(f"[*] 线程数: {threads}")
    print(f"[*] 按 Ctrl+C 可随时中断检测")
    
    # 创建检测器并运行测试
    tester = Kali2025PermissionBypassTester(base_url, threads)
    results = tester.run_comprehensive_test()
    
    # 打印摘要报告
    tester.print_summary_report()
    
    # 保存详细报告
    tester.save_detailed_report()
    
    print(f"\n[*] 检测完成! 详细报告已生成在: {tester.report_dir}/")

if __name__ == "__main__":
    main()